package com.lzx.producer.listener;

import com.lzx.producer.entity.Demo1;
import com.lzx.producer.feign.ConsumerClient;
import com.lzx.producer.mapper.ProducerMapper;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

import javax.annotation.Resource;

/**
 * @author 程序员星星
 * @date 2022/12/26
 * @Description
 */
@RocketMQTransactionListener
public class MyTransactionListener implements RocketMQLocalTransactionListener {
    @Resource
    private ProducerMapper producerMapper;

    @Resource
    private ConsumerClient consumerClient;

    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            Demo1 demo1 = producerMapper.selectById(1);
            demo1.setCount(demo1.getCount() - 1);
            producerMapper.updateById(demo1);
            consumerClient.updateData();
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return RocketMQLocalTransactionState.ROLLBACK;
        }
//        String destination = (String) arg;
//        //把spring的message转换成rocketmq的message
//        org.apache.rocketmq.common.message.Message message = RocketMQUtil.convertToRocketMessage(
//                new StringMessageConverter(),
//                "utf-8",
//                destination,
//                msg
//        );
//        System.out.println(message.getProperties().get("msg"));
    }

    //回查本地事务状态
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        System.out.println("==============>" + msg);
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
